package com.duck.inspection.utils;

import com.alibaba.dashscope.aigc.generation.Generation;
import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.aigc.generation.models.QwenParam;
import com.alibaba.dashscope.common.Message;
import com.alibaba.dashscope.common.MessageManager;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;

public class QianWenChat {
    /**
     * 向阿里云通义千问大模型发送问题并接受返回的答案
     *
     * @param prompt 用户提问的问题
     * @return 大模型返回的答案
     * @throws ApiException           api异常
     */
    public static String callWithMessage(String prompt) throws ApiException
    {
        Generation gen = new Generation();
        try {
            MessageManager msgManager = new MessageManager(10);
            msgManager.add(Message.builder().role(Role.USER.getValue()).content(prompt).build());

            QwenParam param = QwenParam.builder()
                    .model(Generation.Models.QWEN_TURBO)
                    .messages(msgManager.get())
                    .resultFormat(QwenParam.ResultFormat.MESSAGE)
                    .topP(0.8)
                    .enableSearch(true)
                    .build();

            GenerationResult result = gen.call(param);
            return cleanResponse(result.getOutput().getChoices().get(0).getMessage().getContent());
        } catch (Exception e) {
            throw new RuntimeException("模型调用失败", e);
        }
    }

    // 清洗模型响应
    private static String cleanResponse(String text) {
        return text.replace("输出格式：", "")   // 移除冗余标题
                .replaceAll("\\*\\*", ""); // 去除Markdown加粗
    }
}
